import {
  getSearchQuestionList,
  getHotSearch,
  getImDetail,
  getQuestionDetail,
  getProfessions,
  getPublishQuestions
} from '@/api/answer_question'
export default {
  namespaced: true,
  state: () => ({
    relatedAnswer: [], // 相关问答推荐
    relatedQuestion: [], // 相关问题推荐
    isHide: 1, // 是否隐藏 1显示 2隐藏
    // 最新问答列表
    allQuestionListNew: [],
    // 最新问答分页
    allQuestionPagerNew: {
      page: 1,
      limit: 10,
      total: 0
    },
    // 最新问答推荐信息
    recommendData: {},
    // 答疑专业列表
    professionList: [],
    //当前展示第几个TAB
    navTab: 1,
    //搜索结果
    keyword: '',
    //搜索答疑结果
    searchQuestionResult: {},
    //热门搜索
    hotSearch: [],
    //未读信息
    unreadCount: 0,
    //详情ID
    detailId: '',
    //问题状态
    questionStatus: 1,
    //评价详情
    evaluateDetil: '',
    //用户信息
    userInfo: {},
    //问题详情
    questionDetail: [],
    //问题类型 1-课程 2-题库 3-图书 4-其它
    questionType: 4,
    //回复详情
    replys: [],
    //问题来源
    questionOrigin: '',
    //im详情
    imDetail: [],

    // 推荐数据
    recommentData: {},
    //是否对话答疑
    isConversition: false
  }),
  mutations: {
    // 设置最新问答的推荐信息
    setRecommendData(state, data) {
      state.recommendData = data
    },
    // 设置最新问答pager
    setAllQuestionPagerNew(state, data) {
      state.allQuestionPagerNew = data
    },
    // 设置最新问答列表
    setAllQuestionListNew(state, data) {
      state.allQuestionListNew = data
    },
    // 设置专业
    setProfessions(state, data) {
      state.professionList = data
    },
    //设置导航TAB
    setNavTab(state, data) {
      let { currentNavTab } = data
      state.navTab = currentNavTab
    },
    //设置关键字
    setKeyword(state, data) {
      state.keyword = data
    },
    //设置搜索结果
    setSearchQuestionResult(state, data) {
      state.searchQuestionResult = data
    },
    //设置热门搜索
    setHotSearch(state, data) {
      state.hotSearch = data
    },
    //本地增加搜索记录
    addHotSearch(state, data) {
      state.hotSearch.push(data)
    },
    //设置未读提问
    setUnreadQuesCount(state, data) {
      state.unreadCount = data
    },
    //设置对话答疑参数
    setTencentParams(state, data) {
      state.tencentParams = data
    },
    //设置详情ID
    setQuesDetail(state, data) {
      let {
        is_hide = 1,
        recommend_data = {},
        online_reply = {},
        evaluate = {},
        user_info = {},
        status = '0',
        from_attach = '',
        id = '',
        question_type = 4,
        new_reply = [],
        essence_data = [],
        page_view = 0,
        is_essence
      } = data
      let { first_question = {}, add_questions = [] } = online_reply
      state.relatedAnswer = essence_data
      state.relatedQuestion = new_reply
      state.isHide = is_hide
      state.detailId = id
      state.questionStatus = status
      state.evaluateDetil = Object.keys(evaluate).length ? evaluate : null
      state.userInfo = user_info || {}
      let questionDetail = first_question.questions || []
      state.questionDetail =
        +is_essence === 1
          ? questionDetail.filter(item => +item.is_essence === 1)
          : questionDetail
      state.recommentData = recommend_data
      state.questionType = question_type || 4
      state.pageView = page_view
      let replys = first_question.replys || []
      try {
        state.questionOrigin = JSON.parse(from_attach)
        if (!Object.keys(state.questionOrigin).length) state.questionOrigin = ''
      } catch (e) {
        state.questionOrigin = ''
      }
      add_questions.forEach(item => {
        replys.push(...item.questions, ...item.replys)
      })
      state.replys =
        +is_essence === 1
          ? replys.filter(item => +item.is_essence === 1)
          : replys
    },
    //设置答疑状态
    setImDetail(state, data) {
      state.imDetail = data
    },
    //设置答疑帖子的推荐
    setRecommentData(state, data) {
      state.recommentData = data
    },
    //设置是否是对话答疑
    setIsconversition(state, data) {
      state.isConversition = data
    }
  },
  actions: {
    // 拉取最新问答回复列表
    async getPublishQuestions({ commit, state }, params) {
      let { page, limit } = state.allQuestionPagerNew
      let query = {
        page,
        limit
      }

      if (params && params.profession_id) {
        query.profession_id = params.profession_id
      }
      try {
        let res = await getPublishQuestions(query)
        if (res.data) {
          let { list, pager, recommend_data } = res.data
          if (Array.isArray(list)) {
            commit('setAllQuestionListNew', list)
          }

          if (pager) {
            commit('setAllQuestionPagerNew', pager)
          }

          if (recommend_data) {
            commit('setRecommentData', recommend_data)
          }
        }
      } catch (e) {}
    },
    // 拉取专业
    async getProfessions({ commit }, params = {}) {
      try {
        let res = await getProfessions(params)
        if (res.data && Array.isArray(res.data.profession_list)) {
          let professionList = res.data.profession_list || []
          professionList.unshift({
            profession_id: '0',
            profession_name: '全部'
          })
          commit('setProfessions', professionList)
        }
      } catch (err) {}
    },
    //获取搜索结果
    async getSearchQuestionResult({ commit, state }, params) {
      try {
        let { keywords } = params
        let { errcode, errmsg, data } = await getSearchQuestionList(params)
        if (+errcode === 0) {
          let isSaveKeyword = state.hotSearch.some(
            item => item.toString() === keywords.toString()
          )
          if (!isSaveKeyword) commit('addHotSearch', keywords.toString())
          commit('setSearchQuestionResult', data)
          commit('setNavTab', { currentNavTab: 4 })
        }
      } catch (err) {}
    },
    //获取搜索记录
    async getHotSearch({ commit }, params) {
      try {
        let { errcode, errmsg, data } = await getHotSearch(params)
        if (+errcode === 0) {
          commit('setHotSearch', data.keyword_list || [])
        }
      } catch (err) {}
    },
    //获取答疑详情
    async getDayiDetail({ dispatch, commit, state }, { params, context }) {
      let { id, is_unread = 0, spt = 1, is_essence } = params
      //此时需要前端渲染
      if (isNaN(id)) return
      state.relatedAnswer = []
      state.questionDetail = []
      if (+spt === 2) {
        commit('setIsconversition', true)
        await dispatch('getImDetail', { id, context, is_essence })
      } else {
        await dispatch('getQuestionDetail', {
          id,
          is_unread,
          context,
          is_essence
        })
      }
    },
    //获取im详情
    async getImDetail({ commit, state }, params) {
      let { id, context } = params
      let _params = {}
      _params.object_id = isNaN(Number(id)) ? id : +id
      let res = await getImDetail(_params).catch(err => {
        return { data: [] }
      })

      let data = res.data || {}
      let imDetail = data.list || []
      let recommend_data = data.recommend_data || {}
      let teacherInfo = data.teacher_info || {}
      let userInfo = data.user_info || {}
      let firstUserQues = ''
      let firstTeacherAnswer = ''
      let { is_hide = 1 } = data
      state.isHide = is_hide

      imDetail.forEach(item => {
        if (item.from_account === teacherInfo.teacher_im_account) {
          item.avatar = teacherInfo.teacher_avatar
          item.name = teacherInfo.teacher_name
          item.teacher_tag = teacherInfo.teacher_tag
          item.type = 1
        }
        if (item.from_account === userInfo.user_im_account) {
          item.avatar = userInfo.user_avatar
          item.name = userInfo.user_name
          item.type = 2
        }
        if (item.msgbody && item.msgbody[0]) {
          let content = item.msgbody[0].MsgContent
          if (content.Text) {
            item.text = content.Text
            if (!firstUserQues && item.type === 2) firstUserQues = item.text
            if (!firstTeacherAnswer && item.type === 1)
              firstTeacherAnswer = item.text
          }
        }
      })
      imDetail = imDetail.filter(item => item.type)
      imDetail.reverse()
      commit('setImDetail', imDetail)
      commit('setRecommentData', recommend_data)
      commit('setIsConsivation', true)
      // 设置SEO相关
      let title =
        firstUserQues && firstUserQues.length > 26
          ? firstUserQues.slice(0, 26) + '...-之了课堂'
          : firstUserQues + '-之了课堂'
      let keywords =
        firstUserQues && firstUserQues.length > 50
          ? firstUserQues.slice(0, 50) + '...'
          : firstUserQues
      let description =
        firstTeacherAnswer && firstTeacherAnswer.length > 80
          ? firstTeacherAnswer.slice(0, 80) + '...'
          : firstTeacherAnswer
      description = !description
        ? firstUserQues && firstUserQues.length > 80
          ? firstUserQues.slice(0, 80) + '...'
          : firstUserQues
        : description
      let metaData = {
        title: title,
        keywords: keywords,
        description: description
      }
      commit('setMeta', { data: metaData, context }, { root: true })
    },
    //获取问题详情
    async getQuestionDetail({ commit, state }, params) {
      let { id, is_unread, context, is_essence } = params
      let _params = {
        from: 'web'
      }
      _params.object_id = isNaN(Number(id)) ? id : +id
      if (+is_unread) _params.is_unread = '1'
      let res = await getQuestionDetail(_params).catch(err => {
        return { data: [] }
      })
      let data = res.data || {}

      commit('setQuesDetail', { ...data, is_essence })
      // 设置SEO相关
      let { online_reply = {}, tdk = {} } = data
      let { first_question = {} } = online_reply
      let userQues =
        first_question.questions && first_question.questions[0]
          ? first_question.questions[0].question
          : ''
      let teacherReply =
        first_question.replys && first_question.replys[0]
          ? first_question.replys[0].reply_content
          : ''
      let title =
        userQues && userQues.length > 26
          ? userQues.slice(0, 26) + '...-之了课堂'
          : userQues + '-之了课堂'
      let keywords =
        userQues && userQues.length > 50
          ? userQues.slice(0, 50) + '...'
          : userQues
      let description =
        teacherReply.length !== 47
          ? teacherReply.length > 80
            ? teacherReply.slice(0, 80) + '...'
            : teacherReply
          : ''
      description = !description
        ? userQues && userQues.length > 80
          ? userQues.slice(0, 80) + '...'
          : userQues
        : description

      if (tdk) {
        title = tdk.title || title
        keywords = tdk.keywords || keywords
        description = tdk.description || description
      }
      let metaData = {
        title: title,
        keywords: keywords,
        description: description
      }
      commit('setMeta', { data: metaData, context }, { root: true })
    }
  },
  getters: {}
}
